import React, { Component } from 'react'
import {
	StyleSheet,
	View,
	Text,
	FlatList,
	RefreshControl,
	ActivityIndicator,
	DeviceInfo
} from 'react-native'
import {
	createMaterialTopTabNavigator,
	createAppContainer
} from 'react-navigation'
import { connect } from 'react-redux'
import Toast from 'react-native-easy-toast'
import NavigationBar from '../common/NavigationBar'
import actions from '../action'
import PopularItem from '../common/PopularItem'
import NavigationUtil from '../navigator/NavigationUtil'
import FavoriteDao from '../expand/dao/FavoriteDao'
import { FLAG_STORAGE } from '../expand/dao/DataStore'
import FavoriteUtil from '../util/FavoriteUtil'
import TrendingItem from '../common/TrendingItem'
import EventTypes from '../util/EventTypes'
import EventBus from 'react-native-event-bus'

const THEME_COLOR = '#678'

export default class FavoritePage extends Component {
	constructor(props) {
		super(props)
		this.tabNames = ['最热', '趋势']
	}

	render() {
		//导航栏
		let statusBar = {
			backgroundColor: THEME_COLOR,
			barStyle: 'light-content'
		}
		let navigationBar = (
			<NavigationBar
				title={'最热'}
				statusBar={statusBar}
				style={{ backgroundColor: THEME_COLOR }}
			/>
		)

		const TabNavigator = createAppContainer(
			createMaterialTopTabNavigator(
				{
					Popular: {
						screen: props => (
							<FavoriteTabPage
								{...props}
								flag={FLAG_STORAGE.flag_popular}
							/>
						), //初始化Component时携带默认参数 @https://github.com/react-navigation/react-navigation/issues/2392
						navigationOptions: {
							title: '最热'
						}
					},
					Trending: {
						screen: props => (
							<FavoriteTabPage
								{...props}
								flag={FLAG_STORAGE.flag_trending}
							/>
						), //初始化Component时携带默认参数 @https://github.com/react-navigation/react-navigation/issues/2392
						navigationOptions: {
							title: '趋势'
						}
					}
				},
				{
					tabBarOptions: {
						tabStyle: styles.tabStyle,
						upperCaseLabel: false, //是否使标签大写，默认为true
						style: {
							backgroundColor: '#678', //Tab的背景色
							height: 30 //fix开启scrollEnabled后再加Android上初次加载时闪烁问题
						},
						indicatorStyle: styles.indicatorStyle, //标签指示器的样式
						labelStyle: styles.labelStyle //文字的样式
					}
				}
			)
		)

		//注意这里需要将View的样式用flex（踩坑）
		return (
			<View
				style={{
					flex: 1,
					marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0
				}}
			>
				{navigationBar}
				<TabNavigator />
			</View>
		)
	}
}

class FavoriteTab extends Component {
	constructor(props) {
		super(props)
		const { flag } = this.props
		this.storeName = flag
		this.favoriteDao = new FavoriteDao(flag)
	}

	componentDidMount() {
		this.loadData(true)

		EventBus.getInstance().addListener(
			EventTypes.bottom_tab_select,
			(this.listener = data => {
				//data.to表示的是底部tabBar的索引(从0开始)
				if (data.to === 2) {
					//切换到收藏tabbar时候就不刷新进度条了
					this.loadData(false)
				}
			})
		)
	}

	componentWillUnmount() {
		EventBus.getInstance().removeListener(this.listener)
	}

	loadData(isShowLoading) {
		const { onLoadFavoriteData } = this.props
		onLoadFavoriteData(this.storeName, isShowLoading)
	}

	/**
	 * 获取与当前页面有关的数据,注意做补偿(设置默认值)
	 * @return {*}
	 * @private
	 */
	_store() {
		const { favorite } = this.props
		let store = favorite[this.storeName]
		if (!store) {
			store = {
				items: [],
				isLoading: false,
				projectModels: [] //要显示的数据
			}
		}
		return store
	}

	renderItem(data) {
		const item = data.item
		const Item =
			this.storeName === FLAG_STORAGE.flag_popular
				? PopularItem
				: TrendingItem

		return (
			<Item
				projectModel={item}
				onSelect={callback => {
					NavigationUtil.goPage(
						{
							projectModel: item,
							flag: this.storeName,
							callback
						},
						'DetailPage'
					)
				}}
				onFavorite={(item, isFavorite) => this.onFavorite(item, isFavorite)}
			/>
		)
	}

	onFavorite(item, isFavorite) {
		FavoriteUtil.onFavorite(
			this.favoriteDao,
			item,
			isFavorite,
			this.props.flag
		)
		//监听收藏页面的修改，方便同步到最热页面和趋势页面
		if (this.storeName === FLAG_STORAGE.flag_popular) {
			EventBus.getInstance().fireEvent(EventTypes.favorite_changed_popular)
		} else {
			EventBus.getInstance().fireEvent(EventTypes.favorite_changed_trending)
		}
	}

	render() {
		let store = this._store()

		return (
			<View style={styles.container}>
				<FlatList
					data={store.projectModels}
					renderItem={data => this.renderItem(data)}
					keyExtractor={item => '' + (item.item.id || item.item.fullName)}
					refreshControl={
						<RefreshControl
							title={'Loading'}
							titleColor={THEME_COLOR}
							colors={[THEME_COLOR]}
							refreshing={store.isLoading}
							onRefresh={() => this.loadData(true)}
							tintColor={THEME_COLOR}
						/>
					}
				/>
				<Toast ref={'toast'} position={'center'} />
			</View>
		)
	}
}

//订阅
//组件只需要关心与自己有关的state
const mapStateToProps = state => ({
	favorite: state.favorite
})
const mapDispatchToProps = dispatch => ({
	onLoadFavoriteData: (storeName, isShowLoading) =>
		dispatch(actions.onLoadFavoriteData(storeName, isShowLoading))
})

//注意：connect只是个function，并不一定非要放在export后面
const FavoriteTabPage = connect(
	mapStateToProps,
	mapDispatchToProps
)(FavoriteTab)

const styles = StyleSheet.create({
	container: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: '#f5fcff'
	},
	tabStyle: {
		// minWidth: 50 //加载慢的时候会出现样式错乱，这里注释掉
		padding: 0
	},
	labelStyle: {
		fontSize: 13,
		margin: 0
	}
})
